import store from '@/store'
import router from '@/router'
import axios from 'axios'
import { Message } from 'element-ui'

const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  baseURL: 'http://likede2-admin.itheima.net/likede', // url = base url + request url
  timeout: 5000 // request timeout
})

const TimeOut = 3600 // 1小时
// 封装函数 判断token是否过期
function isTImeOut() {
  return (Date.now() - store.getters.tokenTime) / 1000 > TimeOut
}
// request interceptor
service.interceptors.request.use(config => {
  if (store.getters.loginInfo.token) {
    if (isTImeOut()) {
      // 如果接口超时，我们先清空数据
      store.dispatch('user/logout')
      // 跳转登录页面
      router.push('/login')
      // 抛出错误
      return Promise.reject('接口超时')
    }
    config.headers['Authorization'] = `${store.getters.loginInfo.token}`
  }

  return config
}, err => {
  return Promise.reject(err)
})

// response interceptor
service.interceptors.response.use(response => {
  return response
}, err => {
  if (err.response && err.response.data && err.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push('login')
  } else {
    console.log(err.message)
  }
  return Promise.reject(new Error(err))
})

export default service
